package JAVA300.第十二章网络编程;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 接收线程
 */

public class web04_UDP6_ChatThreadReceive implements Runnable{


    private DatagramSocket server;
    private String from;



    public web04_UDP6_ChatThreadReceive(int port,String from) {
        this.from = from;
        try {
            server = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while (true){
            byte[] container = new byte[1024*60];//最多60k
            DatagramPacket packet = new DatagramPacket(container,0,container.length);
            // 3.阻塞式接收方法 receive
            try {
                server.receive(packet);

                //4.分析数据 getData（），getlength()--返回字节数组 byte[]
                byte[] datas = packet.getData();
                String msg = new String(datas,0,datas.length);
                System.out.println("from"+ from+":"+msg);//还原成字符串

                if (msg.equals("bye")){
                    break;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }



        }

        //5.释放资源
        server.close();

    }
}
